﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using Frame.Lib.Core.Log;

namespace Frame.Lib.Core.Dispatch
{
    public class AppDispatch
    {
        private Timer _timer;//调度时钟

        private List<DispatchInfo> _list;     

        public  DateTime LastRunTime//用于监控使用
        {
            get;
            set;
        }

        private static AppDispatch _dispatch;

        public static AppDispatch Dispatch
        {
            get
            {
                if (_dispatch == null)
                {
                    _dispatch = new AppDispatch();

                    Logger.Exception(new Exception("Dispatch=null"));
                }
                return _dispatch;
            }
        }


        public AppDispatch()
        {
            Update();

            _timer = new Timer();
            _timer.Interval = 5000;
            _timer.Elapsed += (sender, e) =>
            {
                _timer.Stop();               
                foreach (DispatchInfo info in _list)
                {
                    TimeSpan span = DateTime.Now - info.LastExecuteTime;

                    if (span.TotalMinutes >= info.Interval)
                    {                            
                        info.Dispatch.Run();
                        info.LastExecuteTime = DateTime.Now;

                        Logger.Exception(new Exception("开始收邮件"));
                    }

                    Logger.Exception(new Exception("span:" + span.TotalMinutes));
                }         
       
                _timer.Start();
                LastRunTime = DateTime.Now;
            }; 
        }

        public void Update()
        {            
            DispatchBO dispatch = new DispatchBO();
            _list = dispatch.GetList().Where(T => T.State == (int)DispatchState.开启).ToList();
            foreach (DispatchInfo info in _list)
            {
                try
                {
                    Type type = Type.GetType(info.Name);
                    object obj = Activator.CreateInstance(type);
                    info.Dispatch = obj as IDispatch;                    
                }
                catch (Exception ex)
                {
                    Logger.Exception(ex);
                }
            }
            _list = _list.Where(T => T.Dispatch != null).ToList();
           
        }
        

        public void Start()
        {
                     
            _timer.Start();            
        }

        public void Stop()
        {
            _timer.Stop();
        }
    }
}
